package net.dreamlu.handler;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

import com.jfinal.handler.Handler;
import com.swetake.util.Qrcode;

public class QRcodeHandler extends Handler {

    @Override
    public void handle(String target, HttpServletRequest request,
            HttpServletResponse response, boolean[] isHandled) {
        // 二维码拦截，对二维码修改
        if (target.startsWith("/api/qrcode-")) {
            String codeInfo = target.substring(12, target.lastIndexOf("."));
            
            byte[] bytes = Base64.decodeBase64(codeInfo);
            Qrcode qrcode = new Qrcode();  
            qrcode.setQrcodeErrorCorrect('M');  
            qrcode.setQrcodeEncodeMode('B');  
            qrcode.setQrcodeVersion(5); // 5 113, 7 139
            
            BufferedImage bi = new BufferedImage(100, 100,BufferedImage.TYPE_INT_RGB);  
            Graphics2D g = bi.createGraphics();  
            g.setBackground(Color.WHITE);   //背景颜色  
            g.clearRect(0, 0, 100, 100);  
            g.setColor(Color.black);    //条码颜色  
            if (bytes.length > 0 && bytes.length < 84) {  
                boolean[][] b = qrcode.calQrcode(bytes);  
                for (int i = 0; i < b.length; i++) {  
                    for (int j = 0; j < b.length; j++) {  
                        if (b[j][i]) {  
                            g.fillRect(j * 2 + 12, i * 2 + 12, 2, 2);  
                        }  
                    }  
                }  
            }  
            g.dispose();  
            bi.flush();
            response.setContentType("image/png");
            try {
                ImageIO.write(bi, "png", response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            isHandled[0] = true;
            return;
        }
        nextHandler.handle(target, request, response, isHandled);
    }

}
